<template>
  <el-dialog :visible.sync="dialog" :title="isAdd ? '新增用户' : '编辑用户'" append-to-body width="600px">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="70px" label-position="right">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" :disabled="!isAdd" />
      </el-form-item>
      <el-form-item label="姓名" prop="nickname">
        <el-input v-model.number="form.nickname" />
      </el-form-item>
      <el-form-item v-if="form.username!=='admin'" label="状态" prop="status">
        <el-radio v-for="item in dictobj['status']" :key="item.value" v-model="form.status" :label="item.value">{{ item.label }}</el-radio>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio v-for="item in dictobj['sex_status']" :key="item.value" v-model="form.sex" :label="item.value">{{ item.label }}</el-radio>
      </el-form-item>
      <el-form-item v-if="form.username!=='admin'" label="类型" prop="type">
        <el-radio v-for="item in dictobj['user_type_status']" :key="item.value" v-model="form.type" :label="item.value">{{ item.label }}</el-radio>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model.number="form.phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>

      <el-form-item v-if="form.username!=='admin'" style="margin-bottom: 0px;" label="角色">
        <el-select v-model="roleIds" style="width: 450px;" multiple placeholder="请选择">
          <el-option v-for="(item, index) in roles" :key="item.name + index" :disabled="level !== 1 && item.level <= level" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  add,
  edit
} from '@/api/system/user'
import {
  getAll,
  getLevel
} from '@/api/system/role'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: {

  },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    dictobj: {
      type: Object,
      required: true
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!this.isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      dialog: false,
      loading: false,
      form: {
        username: '',
        email: '',
        status: '0',
        roles: [],
        phone: null,
        type: 'BACKEND',
        sex: '1'
      },
      roleIds: [],
      roles: [],
      style: 'width: 184px',
      level: 2,
      // 这个是数据校验
      rules: {
        username: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 20,
          message: '长度在 2 到 20 个字符',
          trigger: 'blur'
        }
        ],
        email: [{
          required: true,
          message: '请输入邮箱地址',
          trigger: 'blur'
        },
        {
          type: 'email',
          message: '请输入正确的邮箱地址',
          trigger: 'blur'
        }
        ],
        phone: [{
          required: true,
          trigger: 'blur',
          validator: validPhone
        }],
        status: [{
          required: true,
          message: '状态不能为空',
          trigger: 'blur'
        }],
        type: [{
          required: true,
          message: '用户类型不能为空',
          trigger: 'blur'
        }],
        nickname: [{
          required: true,
          message: '姓名不能为空',
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    const explorer = navigator.userAgent
    if (explorer.indexOf('Chrome') >= 0) {
      this.style = 'width: 184px'
    } else {
      this.style = 'width: 172px'
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.roleIds.length === 0) {
            this.$message({
              message: '角色不能为空',
              type: 'warning'
            })
          } else {
            this.loading = true
            this.form.roles = []
            const _this = this
            this.roleIds.forEach(function(data, index) {
              const role = {
                id: data
              }
              _this.form.roles.push(role)
            })
            if (this.isAdd) {
              this.doAdd()
            } else this.doEdit()
          }
        } else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          message: '默认密码：123456',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'] && this.$refs['form'].resetFields()
      this.deptId = null
      this.jobId = null
      this.roleIds = []
      this.form = {
        username: '',
        email: '',
        status: '0',
        roles: [],
        phone: null,
        type: 'BACKEND',
        sex: '1',
        nickname: ''
      }
    },
    getRoles() {
      getAll().then(res => {
        this.roles = res.data.roles
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    isvalidPhone(str) {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      return reg.test(str)
    },
    selectFun(node, instanceId) {
      this.getJobs(node.id)
    },
    getRoleLevel() {
      getLevel().then(res => {
        console.log(res)
        this.level = res.level
      }).catch(err => {
        console.log(err.response.data.message)
      })
    }
  }
}
</script>

<style scoped>

</style>
